package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.UpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.dto.SetmealDto;
import com.itheima.entity.Category;
import com.itheima.entity.Dish;
import com.itheima.entity.Setmeal;
import com.itheima.entity.SetmealDish;
import com.itheima.service.CategoryService;
import com.itheima.service.DishService;
import com.itheima.service.SetmealDishService;
import com.itheima.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/setmeal")
public class SetmealController {
    @Autowired
    private SetmealService setmealService;
    @Autowired
    private SetmealDishService setmealDishService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private DishService dishService;

    /**
     * 新增套餐信息
     *
     * @param setmealDto
     * @return
     */
    @CacheEvict(value = "setmeal",key = "#setmealDto.categoryId +'::1'")
    @PostMapping
    public R save(@RequestBody SetmealDto setmealDto) {
        log.info("新增套餐信息:" + setmealDto);
        boolean b = setmealService.saveWithDish(setmealDto);
        return b ? R.success("成功") : R.error("失败");
    }

    /**
     * 套餐分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R page(Integer page, Integer pageSize, String name) {
        log.info("套餐分页查询: page:" + page + " pageSize:" + pageSize + " name:" + name);
        //配置分页
        Page<Setmeal> setmealPage = new Page<>(page, pageSize);
        //设置查询条件
        LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(name != null, Setmeal::getName, name)
                .orderByAsc(Setmeal::getUpdateTime);
        setmealService.page(setmealPage, wrapper);

        //配置dto分页
        Page<SetmealDto> setmealDtoPage = new Page<>(page, pageSize);
        //分页基本信息copy
        BeanUtils.copyProperties(setmealPage, setmealDtoPage, "records");
        //对象的copy 先拿到records
        List<SetmealDto> setmealDtoList = setmealPage.getRecords().stream().map(item -> {
            SetmealDto setmealDto = new SetmealDto();
            //基本字段copy
            BeanUtils.copyProperties(item, setmealDto);
            //根据item(setmeal)的分类id 查分类的名字 然后赋给setmealDto的分类属性
            Category category = categoryService.getById(item.getCategoryId());
            if (category != null) {
                setmealDto.setCategoryName(category.getName());
            }
            //返回封装后的信息
            return setmealDto;
        }).collect(Collectors.toList());
        setmealDtoPage.setRecords(setmealDtoList);
        return R.success(setmealDtoPage);
    }

    /**
     * 根据id查询套餐信息
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R getById(@PathVariable Long id) {
        log.info("根据id'" + id + "'查询套餐信息");
        //查询套餐基本信息
        Setmeal setmeal = setmealService.getById(id);
        //查询套餐和菜品的关联信息
        LambdaQueryWrapper<SetmealDish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(id != null, SetmealDish::getSetmealId, id);
        List<SetmealDish> setmealDishList = setmealDishService.list(wrapper);

        SetmealDto setmealDto = new SetmealDto();
        BeanUtils.copyProperties(setmeal, setmealDto);
        setmealDto.setSetmealDishes(setmealDishList);

        //查询套餐的分类id 查分类的名字
        Long categoryId = setmeal.getCategoryId();
        if (categoryId != null) {
            Category category = categoryService.getById(categoryId);
            String categoryName = category.getName();
            setmealDto.setCategoryName(categoryName);
        }
        return R.success(setmealDto);
    }

    /**
     * 修改套餐
     *
     * @param setmealDto
     * @return
     */
    @CacheEvict(value = "setmeal",key = "#setmealDto.categoryId +'::1'")
    @PutMapping
    public R update(@RequestBody SetmealDto setmealDto) {
        log.info("修改套餐:" + setmealDto.toString());
        boolean b = setmealService.updateWithDish(setmealDto);
        return b ? R.success("成功") : R.error("失败");
    }

    /**
     * 批量修改套餐的启停售状态
     *
     * @param ids
     * @param status
     * @return
     */
    @PostMapping("/status/{status}")
    public R updateStatus(@RequestParam List<Long> ids, @PathVariable Integer status) {
        log.info("批量修改套餐的启停售状态:" + ids + " status:" + status);
        UpdateChainWrapper<Setmeal> wrapper = setmealService.update();
        boolean b = wrapper.in(ids != null, "id", ids).set("status", status).update();
        return b ? R.success("成功") : R.error("失败");
    }

    /**
     * 批量删除套餐
     *
     * @param ids
     * @return
     */
    //只要删除,就清空所有缓存
    @CacheEvict(value = "setmeal",allEntries = true)
    @DeleteMapping
    public R delete(@RequestParam List<Long> ids) {
        log.info("批量删除套餐:" + ids);
        boolean b = setmealService.deleteWithDish(ids);
        return b ? R.success("成功") : R.error("失败");
    }

    /**
     * 根据分类id查询套餐list
     * @param setmeal
     * @return
     */
    //K = setmeal::xxx::1
    //unless: 返回值中data属性==null不添加,!=null添加
    @Cacheable(value = "setmeal",key = "#setmeal.categoryId +'::'+ #setmeal.status",unless = "#result.data == null")
    @GetMapping("/list")
    public R getList(Setmeal setmeal){
        log.info("根据分类id'{}'查询启用套餐list",setmeal);
        LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(setmeal.getCategoryId()!=null,Setmeal::getCategoryId,setmeal.getCategoryId())
                .eq(setmeal.getStatus()!=null,Setmeal::getStatus,setmeal.getStatus())
                .orderByDesc(Setmeal::getUpdateTime);
        List<Setmeal> list = setmealService.list(wrapper);
        return R.success(list);
    }

    /**
     * 根据id查询套餐或者菜品
     * @param id
     * @return
     */
    @GetMapping("/dish/{id}")
    public R getDish(@PathVariable Long id){
        log.info("根据id查询套餐或者菜品:{}",id);
        //套餐查询所有的菜
        LambdaQueryWrapper<SetmealDish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(id!=null,SetmealDish::getSetmealId,id);
        List<SetmealDish> setmealDishList = setmealDishService.list(wrapper);
        //图片
        setmealDishList = setmealDishList.stream().map(item -> {
            Dish dish = dishService.getById(item.getDishId());
            item.setImage(dish.getImage());
            return item;
        }).collect(Collectors.toList());
        return R.success(setmealDishList);
    }
}
